// 通过统一配置入口导入模块
const pathImport = require('../../../config/path_resolver.js').pageHelper;
const { pageHelper, cloudHelper, routerHelper } = pathImport;

const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { userStore } = require('../../../config/path_resolver.js').getRootConfigPath('path_resolver.js').getProjectStorePath('modules/user/index');
const projectHelper = require('../../../config/path_resolver.js').pageHelper;
const { logEvent } = require('../../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../../helpers/network_helper.js');

Page({
  data: {
    // 页面数据
    isLoad: false,
    
    // 页面加载状态
    loading: false,
    error: null,
    
    // 加载提示文本
    loadingText: '数据加载中...'
  },
  
  onLoad: async function(options) {
    // 创建状态绑定 - 用户数据
    this.userStoreBindings = createStoreBindings(this, {
      store: userStore,
      fields: ['isLogin', 'user', 'isAdmin'],
      actions: ['init', 'loginSilence']
    });
    
    // 设置当前项目为PLM
    projectHelper.setCurrentProject('plm');
    
    // 网络检测
    const net = await getNetworkStatus();
    if (!net.isConnected) {
      wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
    } else if (net.networkType === '2g') {
      wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
    }
    listenNetworkStatus((res) => {
      if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
      else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
    });
    logEvent('page_load', { page: 'plm_default_index' });
    
    // 初始化加载数据
    this._init();
  },
  
  /**
   * 页面初始化
   */
  _init: async function() {
    await this._checkLoginState();
    
    this.setData({
      isLoad: true
    });
  },
  
  /**
   * 检查登录状态并加载数据
   */
  _checkLoginState: async function() {
    try {
      // 获取loading组件实例
      this.loadingComp = this.selectComponent('#loading');
      
      // 使用MobX初始化用户状态（会自动检查登出标记）
      const initResult = this.init();
      
      if (!initResult) {
        // 尝试静默登录
        // 显示loading
        if (this.loadingComp) this.loadingComp.show('登录中...');
        
        const loginResult = await this.loginSilence();
        
        // 隐藏loading
        if (this.loadingComp) this.loadingComp.hide();
        
        if (!loginResult) {
          console.log('静默登录失败，显示未登录状态');
          return false;
        }
      }
      
      return true;
    } catch (err) {
      console.error('登录检查出错', err);
      // 隐藏loading
      if (this.loadingComp) this.loadingComp.hide();
      return false;
    }
  },
  
  /**
   * 统一的页面导航方法，使用路由辅助模块
   */
  url: function(e) {
    const url = e.currentTarget.dataset.url;
    const params = e.currentTarget.dataset.params || {};
    
    console.log('[PLM_INDEX] 准备导航到:', url);
    
    // 使用routerHelper导航
    routerHelper.navigateTo(url, params);
  },

  /**
   * 跳转到项目列表
   */
  gotoProjectList: function() {
    this.url({
      currentTarget: {
        dataset: {
          url: '/projects/plm/pages/project/list/project_list'
        }
      }
    });
  },
  
  /**
   * 跳转到项目管理
   */
  gotoProjectManage: function() {
    this.url({
      currentTarget: {
        dataset: {
          url: '/projects/plm/pages/project/manage/project_manage'
        }
      }
    });
  },
  
  /**
   * 跳转到新建项目
   */
  gotoCreateProject: function() {
    this.url({
      currentTarget: {
        dataset: {
          url: '/projects/plm/pages/project/edit/project_edit'
        }
      }
    });
  },
  
  /**
   * 跳转到角色模拟器
   */
  gotoRoleSimulator: function() {
    this.url({
      currentTarget: {
        dataset: {
          url: '/projects/plm/pages/project/tools/role_simulation'
        }
      }
    });
  },
  
  /**
   * 跳转到资料管理
   */
  gotoResourceManage: function() {
    this.url({
      currentTarget: {
        dataset: {
          url: '/projects/plm/pages/resource/list/resource_list'
        }
      }
    });
  },
  
  /**
   * 跳转到工艺管理
   */
  gotoProcessManage: function() {
    this.url({
      currentTarget: {
        dataset: {
          url: '/projects/plm/pages/process/list/process_list'
        }
      }
    });
  },
  
  /**
   * 跳转到质量管理
   */
  gotoQualityManage: function() {
    this.url({
      currentTarget: {
        dataset: {
          url: '/projects/plm/pages/quality/list/quality_list'
        }
      }
    });
  },
  
  /**
   * 跳转到供应链
   */
  gotoSupplyChain: function() {
    this.url({
      currentTarget: {
        dataset: {
          url: '/projects/plm/pages/supply/list/supply_list'
        }
      }
    });
  },
  
  /**
   * 跳转到分析看板
   */
  gotoAnalytics: function() {
    this.url({
      currentTarget: {
        dataset: {
          url: '/projects/plm/pages/analytics/dashboard/analytics_dashboard'
        }
      }
    });
  },
  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: async function() {
    wx.stopPullDownRefresh();
  },
  
  /**
   * 页面卸载时清理MobX绑定
   */
  onUnload: function() {
    this.userStoreBindings.destroyStoreBindings();
  }
}); 